package com.lsh.oms.provider.service.order.frozen;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.oms.api.model.es.OrderHeadForEs;
import com.lsh.oms.api.model.order.OrderReceiptPayNotifyDTO;
import com.lsh.oms.api.service.order.frozen.IOrderReceiptFrozenRestPayService;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.enums.PayStatus;
import com.lsh.oms.core.enums.SignStatus;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.proxy.service.EsProxy;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.other.ShippingOrderService;
import com.lsh.oms.core.service.other.SignOrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 17/5/12
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "rest", timeout = 30000)
@Path("order/pay")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8})
@Deprecated
public class OrderReceiptFrozenRestPayServiceImpl implements IOrderReceiptFrozenRestPayService {

    private static Logger logger = LoggerFactory.getLogger(OrderReceiptFrozenRestPayServiceImpl.class);

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private SignOrderService signOrderService;

    @Autowired
    private EsProxy esProxy;

    @Autowired
    private ShippingOrderService shippingService;


    @POST
    @Path("notify_false")
    @Override
    @Deprecated
    public String payNotify(OrderReceiptPayNotifyDTO orderReceiptPayNotifyDTO) {

        JSONObject res = new JSONObject();
        JSONObject content = new JSONObject();
        res.put("ret", "0");

        logger.info("orderReceiptPayNotifyDTO is " + orderReceiptPayNotifyDTO);

        if (!orderReceiptPayNotifyDTO.getPay_code().equals("SUCCESS")) {
            res.put("ret", "1000");
            return res.toJSONString();
        }

        try {

            OrderSignHead orderSignHead = new OrderSignHead();
            orderSignHead.setReceiptOrderId(Long.parseLong(orderReceiptPayNotifyDTO.getTrade_id()));
            orderSignHead.setPayType(Integer.parseInt(orderReceiptPayNotifyDTO.getChannel_type()));
            //1  未支付
            orderSignHead.setPayStatus(PayStatus.PAID.getValue());
            //1未到账 2已到账 3 已支付
            orderSignHead.setStatus(SignStatus.ARRIVAL.getIndex());
            int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            orderSignHead.setConfirmAt(time);

            OrderSignHead oshHead = signOrderService.getSignHeadBySignCode(Long.parseLong(orderReceiptPayNotifyDTO.getTrade_id()));
            long orderCode = oshHead.getOrderId();

//            signOrderService.updatePayStatus(orderSignHead, orderCode ,oshHead.getShippingOrderId());

            OrderHead orderHead = orderQueryService.findByCode(orderCode, false, false);

//            this.notifyEs(orderSignHead, orderCode, OrderFactory.getMarketName(orderHead),OrderFactory.getProviderId(orderHead), oshHead.getMoney(),"orderReceiptPayNotifyDTO.getTrade_id()-payment");
            //异步处理
//            smsService.toSignSMS(oshHead, orderHead, "");

            content.put("return_code", "SUCCESS");
            content.put("return_msg", "OK");
        } catch (Exception ex) {
            ex.printStackTrace();
            res.put("ret", "1000");
            content.put("return_code", "FAIL");
        }

        res.put("content", content);
        return res.toJSONString();
    }


    /**
     * 通知es
     *
     * @param orderSignHead 订单号
     * @param logSign       唯一标识
     */
    private void notifyEs(OrderSignHead orderSignHead, Long orderCode, String marketName,String providerId ,BigDecimal money, String logSign) {

        OrderShippingHeadWithBLOBs osh = shippingService.getBolbs(orderCode);
        if (osh == null) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, orderCode + "notifyEs-此订单未生成发货单.请查询");
        }

        try {

            if (StringUtils.isNotBlank(marketName)) {
                orderSignHead.setMarketName(marketName);
            }

            orderSignHead.setProviderId(providerId);
            orderSignHead.setHgReceiptStatus(0);
            orderSignHead.setFinalMoney(money);

            logger.info(logSign + "pay-ES入参新建签收单是-- " + JsonUtils.obj2Json(orderSignHead));
            esProxy.editIndex(orderSignHead, logSign);

            OrderShippingHeadWithBLOBs oshEs = new OrderShippingHeadWithBLOBs();
            oshEs.setShippingOrderId(osh.getShippingOrderId());
            oshEs.setStatus(2);
            logger.info(logSign + "ES入参修改发货是-- " + JsonUtils.obj2Json(oshEs));
            esProxy.editIndex(oshEs, logSign);
            OrderHeadForEs ohEs = new OrderHeadForEs();
            ohEs.setOrderCode(orderCode);
            ohEs.setOrderStatus(OrderStatus.ORDER_SIGN.getIndex());
            logger.info(logSign + "ES入参修改订单是-- " + JsonUtils.obj2Json(ohEs));
            esProxy.editIndex(ohEs, logSign);
        } catch (Throwable e) {
            logger.info(logSign + "签收单号" + orderSignHead.getReceiptOrderId() + ",生成发货单同步es失败。");
            logger.info(e.getMessage(), e);
        }
    }
}
